
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:interview/components/app/app_prompt_overlay.dart';
import 'package:path_provider/path_provider.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/controller/user_controller.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/logger.dart';
import 'package:screenshot/screenshot.dart';
import 'package:qr_flutter/qr_flutter.dart';

class ShareOverlay {
  static OverlayEntry? _overlayEntry;
  static late AnimationController _animationController;
  static late Animation<double> _opacityAnimation;
  static final ScreenshotController screenshotController = ScreenshotController();
  static final userController = Get.find<UserController>();
  static const gallerySaverChannel = MethodChannel('native_gallery_saver');



  static void show({
    required BuildContext context,
    required AppColors theme,
    required String qrString,
    required String title,
  }) {
    // 如果已经显示，避免重复添加
    if (_overlayEntry != null) return;

    final screenSize = MediaQuery.of(context).size;

    // 初始化动画控制器
    _animationController = AnimationController(
      vsync: Overlay.of(context),
      duration: const Duration(milliseconds: 180),
    );

    _opacityAnimation = CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    );

      
    Future<void> _captureAndSave() async {
      try {
        // 1. 截图
        final Uint8List? image = await screenshotController.capture();
        if (image == null) return;

        // 2. 获取存储路径
        final directory = await getTemporaryDirectory();
        final imagePath = '${directory.path}/screenshot_${DateTime.now().millisecondsSinceEpoch}.png';
        final imageFile = File(imagePath);
        // 3. 保存图片到本地文件
        await imageFile.writeAsBytes(image);
        Logger.info("查看路径 ${imageFile.path}"  , tag: "_captureAndSave");
        final result = await gallerySaverChannel.invokeMethod('saveToGallery', {'filePath': imageFile.path});
        AppPromptOverlay.show(context: context, message: "保存二维码成功");
        hide();
        Logger.info("保存图片成功$result" , tag: 'saveToGallery');
      } catch (e) {
        Logger.error("保存失败: $e" , tag: "_captureAndSave");
      }
    }


    _overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Stack(
          children: [
            // 半透明背景蒙层
            GestureDetector(
              onTap: hide,
              child: Container(
                width: screenSize.width,
                height: screenSize.height,
                color: Colors.black.withOpacity(0.5), // 半透明背景
              ),
            ),
            // 弹框内容居中
            Center(
              child: FadeTransition(
                opacity: _opacityAnimation,
                child: Material(
                  color: Colors.transparent,
                  child: Screenshot(
                controller: screenshotController,
                child: Container(
                  margin: const EdgeInsets.symmetric(horizontal: 32), // 增加外边距
                  decoration: BoxDecoration(
                    color: theme.subjectPure,
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            // 顶部标题与图标
                            Padding(
                              padding: EdgeInsets.only(bottom: 24),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Image.asset(
                                    "${AppEnumAssets.basePath}icon.png",
                                    width: 24,
                                    height: 24,
                                  ),
                                  const SizedBox(width: 8),
                                  Text( "面试通，速通企业面试题",style: TextStyle(fontSize: 16,color: theme.contrastPure, fontWeight: FontWeight.bold),
                                  ),
                                ],
                              ),
                            ),
                            // 中间文本内容
                            Text(
                              title,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 14,
                                color: theme.contrastMix3,
                                fontWeight: FontWeight.w500
                              ),
                            ),
                            QrImageView(
                              data: qrString,
                              version: QrVersions.auto,
                              size: 240.0,
                              padding: const EdgeInsets.all(8),
                            ),
                          ],
                        ),
                      ),
                      // 底部分享栏
                      Container(
                        width: double.infinity,
                        decoration: BoxDecoration(
                          borderRadius: const BorderRadius.only(
                            bottomLeft: Radius.circular(12),
                            bottomRight: Radius.circular(12),
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Padding(
                              padding: EdgeInsets.only(left: 12), 
                              child: Text('分享来自 ${userController.getUser()?.username}',style: TextStyle(fontSize: 12,color: theme.contrastMix3,))
                            ),
                            Container(
                              padding: EdgeInsets.symmetric(vertical:12 , horizontal: 16),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(12),
                                  bottomRight: Radius.circular(12)
                                ),
                                color: theme.subjectMix2,
                              ),
                              child: GestureDetector(
                                onTap: _captureAndSave,
                                child:  Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Icon(Icons.file_download_sharp, size: 14, color: theme.contrastMix3),
                                    const SizedBox(width: 4),
                                    Text(
                                      "保存图片",
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: theme.contrastMix3,
                                      ),
                                    ),
                                  ],
                                )
                              )
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
                ),
              ),
            ),
          ],
        );
      },
    );

    // 插入 Overlay
    Overlay.of(context).insert(_overlayEntry!);

    // 开始播放淡入动画
    _animationController.forward();
  }

  // 隐藏 Overlay
  static void hide() async {
    if (_overlayEntry != null) {
      // 播放淡出动画
      await _animationController.reverse();
      _overlayEntry?.remove();
      _overlayEntry = null;
      _animationController.dispose();
    }
  }
}
